<?php
namespace Partner\Controller;

use Utuo\BackgroundController;

class AdController extends BackgroundController{
	
	// 初始化
	public function _initialize() {
		$this->setControllerTitle('合作商广告管理');
		$this->setActionTitle(array(
				'index' => '广告列表',
				'add' =>'添加广告 ',
				'recycle' => '回收站',
				'modify' => '修改广告'
		));
		$this->setActionNav(array(
			'index',
			'add',
			'recycle'
		));
	}
	
	// 文告列表
	public function indexAction() {
		$this->getAdList(0);
	}
	
	// 添加广告页
	public function addAction(){
		$this->display();
	}
	
	// 提交添加广告
	public function addPostAction(){
		$d = D('PartnerAd');
		if ($d->create()) {
			$d->partner = $this->aid;
			$d->content = htmlspecialchars_decode($d->content);
			if ($d->add()) {
				$this->ajaxSuccess('添加广告成功');
			} else {
				$this->ajaxError($d->getError());
			}
		} else {
			$this->ajaxError($d->getError());
		}
	}
	
	// 修改页面
	public function modifyAction(){
		$id = I('id', 0, 'intval');
		$ad = M('PartnerAd')->find($id);
		$this->checkAdmin($ad['partner']);
		$ad['content'] = htmlspecialchars_decode($ad['content']);
		$this->assign('ad', $ad);
		$this->display();
	}
	
	// 提交修改
	public function modifyPostAction() {
		$d = D('PartnerAd');
		if ($d->create()) {
			$d->cid = $this->aid;
			$d->content = htmlspecialchars_decode($d->content);
			$this->checkAdmin(null,M("PartnerAd"),"partner");
			if (false !== $d->save()) {
				$this->ajaxSuccess('修改广告成功');
			} else {
				$this->ajaxError($d->getError());
			}
		} else {
			$this->ajaxError($d->getError());
		}
	}
	
	// 移除广告
	public function removePostAction() {
		$this->checkAdmin(null,M("PartnerAd"),"partner");
		$this->ajaxRemove('partnerAd');
	}
	
	
	// 恢复广告
	public function restorePostAction(){
		$this->checkAdmin(null,M("PartnerAd"),"partner");
		$this->ajaxRestore('partnerAd');
	}
	
	
	// 彻底删除
	public function deletePostAction(){
		$this->checkAdmin(null,M("PartnerAd"),"partner");
		$this->ajaxDelete('partnerAd');
	}
	
	
	// 回收站
	public function recycleAction() {
		$this->getAdList(1);
	}
	
	// 获得广告列表 
	public function getAdList($is_deleted) {
		$d = D("PartnerAd");
		$condition = array(
				'is_deleted' => $is_deleted,
				'partner' => $this->aid,
		);
		$adLists = $d->where($condition)->limit($this->pageSize)->page($this->getPage())->select();
		$count = $d->where($condition)->count();
		$this->assign('adLists', $adLists);
		$this->showPage($count, $this->pageSize);
		$this->display();
	}
	
	// 获得广告列表
	public function getAdListPostAction() {
		$p = I('get.p',1,'intval');
		$pageSize = 10;
		$d = M("PartnerAd")->field("id,name,pic")->where(array('partner' => $this->aid, 'is_deleted' => 0));
		$partnerAdLists = $d->limit(($p-1)*$pageSize.','.$pageSize)->order("id desc")->select();
		if ($partnerAdLists || !$d->getError()) {
			$this->ajaxSuccess('', $partnerAdLists);
		} else {
			$this->ajaxError("获取广告列表失败");
		}
	}
	
}